package com.example.xymarket.adapter;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xymarket.adapter.holder.MessageViewHolder;
import com.example.xymarket.common.ChatConfig;
import com.example.xymarket.common.Info;
import com.example.xymarket.R;
import com.farsunset.cim.sdk.android.model.Message;

import java.util.List;

public class MessageListAdapter extends RecyclerView.Adapter<MessageViewHolder>{

    private List<Message> list;

    public MessageListAdapter(List<Message> list)
    {
        this.list=list;
    }


    @Override
    public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if(viewType==0) {
            return new MessageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message, parent, false));
        }
        else {
            return new MessageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_messgae2, parent, false));
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (list.get(position).getSender().equals(String.valueOf(Info.getMyUserInfo().getId()))) {
            return 1;
        } else {
            return 0;
        }
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
        Message message = list.get(position);
        if(message.getSender().equals(ChatConfig.me.id))
        {
            holder.user_info.setText(ChatConfig.me.name);
            holder.imageView.setImageResource(ChatConfig.me.avatar);
            holder.constraintLayout.setBackgroundColor(Color.rgb(255,255,255));
        }
        else
        {
            holder.user_info.setText(ChatConfig.him.name);
            holder.imageView.setImageResource(ChatConfig.him.avatar);
        }
        holder.content.setText(message.getContent());
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void add(Message message) {
        list.add(message);
        notifyItemInserted(list.size());
    }

}
